package com.fit.pages.user;

import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.services.PropertyAccess;
import org.apache.tapestry5.util.EnumSelectModel;

import com.fit.annotations.AdminAccess;
import com.fit.annotations.UserAccess;
import com.fit.dao.user.UserDAO;
import com.fit.entities.User;
import com.fit.model.glov.GenericSelectModel;
import com.fit.model.type.UserType;
import com.fit.model.user.MD5;

@AdminAccess
public class EditUser {

	@Property
	@Persist
	private User user;

	@Inject
	private UserDAO userDAO;

	@Property
	private String newPassword;

	@Component
	private Form editForm;

	@InjectPage
	private ManageUsers manage;

	@Property
	@Persist
	private UserType userType;


	@Inject
	private PropertyAccess access;
	
	@Inject
	private Messages messages;



	public SelectModel getTypes() {
		return new EnumSelectModel(UserType.class, messages);
	}

	Object onActivate(String username) {
		manage.setError("");
		manage.setConfirmation("");
		User u = userDAO.findByUsername(username);
		if (u != null) {
			user = u;
		}
		if (user == null) {
			manage.setError("Error");
			return manage;
		}
		return null;
	}

	Object onSubmitFromEditForm() {
		manage.setError("");
		manage.setConfirmation("");
		try {
			if (newPassword != null) {
				user.setPassword(MD5.md5(newPassword));
			}
			if (userType !=null && !user.getType().equalsIgnoreCase(userType.toString())) {
				user.setType(userType.toString());
			}

			userDAO.update(user);
			manage.setConfirmation("Successfully edited.");
			return manage;
		} catch (Exception e) {
			manage.setError("Error.");
			return manage;
		}
	}


}
